from django.core.paginator import Paginator, EmptyPage
from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from haystack.views import SearchView

from apps.contents.utils import get_categories
from apps.goods.models import GoodsCategory, SKU, GoodsVisitCount
from apps.goods.utils import get_breadcrumb
from meiduo_mall.settings.dev import logger
from apps.goods.utils import get_breadcrumb, get_goods_specs

"""
商品列表页接口文档：
    路由：list/<int:category_id>/skus/
    请求方式：GET
    参数：查询参数    category_id   string   必传　　商品分类id,第三级分类（路径参数）
    　　　　　　　　　 page         string   必传　　当前页码（查询字符串参数）
                    page_size    string   必传    每页数量（查询字符串参数）
                    ordering     string   必传　　　排序方式（查询字符串参数）
    响应结果： json
            {
    "code":0,
    "errmsg": "ok",
    "breadcrumb": breadcrumb,  # 面包屑数据
    "list":{
        "id":"12",
        "default_image_url":"http://xxxx",
        "name":"apple",
        "price":"1289.00"
    },
    "count":5  # 分页总数
} 

"""
class ListView(View):
    """商品列表页"""
    def get(self, request, category_id):
        """提供商品列表页"""
        # 1.接收参数
        # 当前页面  page
        page = request.GET.get('page')
        # 页面显示页数  page_size
        page_size = request.GET.get('page_size')
        # 排序参数  ordering
        sort = request.GET.get('ordering')

        # 2.校验参数--category_id  是否真的有
        try:
            cat3 = GoodsCategory.objects.get(pk=category_id)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '参数有误! '})

        # 3.根据 cat3 去SKU表 查询对应的数据
        # SKU.objects.filter(category_id=category_id)
        skus = SKU.objects.filter(category=cat3, is_launched=True).order_by(sort)

        # 4.获取面包屑组件数据 cat3--cat2-cat1
        breadcrumb = get_breadcrumb(cat3)

        # 5.将skus 进行分页处理
        paginator = Paginator(skus, page_size)
        # 获取总页数
        total_page = paginator.num_pages
        # 获取当前页的 数据对象  skus
        page = paginator.page(page)

        # 6.将python对象的查询集 数据---转换成 { [ {}]} json格式
        data_list = []
        for sku in page:
            data_list.append({
                "id": sku.id,
                "default_image_url": sku.default_image.url,
                "name": sku.name,
                "price": sku.price  # Decimal('6499.00')
            })

        # 7.返回前端
        return JsonResponse({
            'code': 0,
            'errmsg': 'OK',
            'breadcrumb': breadcrumb,
            'list': data_list,
            'count': total_page
        })



"""
热销商品页借口文档：
    路由：　　　/hot/(?P<category_id>\d+)/
    请求方式： GET
    参数：路径参数　　　category_id   string 必传  商品分类id 第三级分类
    响应结果：json    code errmsg  hot_skus[]  id(sku编号) default_image_url  name  price
                    {
    "code":"0",
    "errmsg":"OK",
    "hot_skus":[
        {
            "id":6,
            "default_image_url":"http://image.meiduo.site:8888/group1/M00/00/02/CtM3BVrRbI2ARekNAAFZsBqChgk3141998",
            "name":"Apple iPhone 8 Plus (A1864) 256GB 深空灰色 移动联通电信4G手机",
            "price":"7988.00"
        },
        {
            "id":14,
            "default_image_url":"http://image.meiduo.site:8888/group1/M00/00/02/CtM3BVrRdMSAaDUtAAVslh9vkK04466364",
            "name":"华为 HUAWEI P10 Plus 6GB+128GB 玫瑰金 移动联通电信4G手机 双卡双待",
            "price":"3788.00"
        }
    ]
}
"""
class HotGoodsView(View):
    def get(self, request, category_id):
        # 校验category_id
        try:
            GoodsCategory.objects.get(pk=category_id)
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code":400, "errmsg":"分类不存在"})
        # 根据category_id查询对应的id，排序－降序　切片[1；２]
        skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by('-sales')[:2]

        # python对象－－[{}]
        hot_list = []
        for sku in skus:
            hot_list.append({
                'id': sku.id,
                'default_image_url': sku.default_image.url,
                'name' : sku.name,
                'price' : sku.price
            })

        # 返回响应
        return JsonResponse({'code':0, 'errmsg':'ok', 'hot_skus':hot_list})


class MySearchView(SearchView):
    # 重写父类  create_response
    def create_response(self):
        # 1.接收参数
        query = self.request.GET.get('q')

        # 2.获取  haystack 返回的数据
        context = self.get_context()

        # 3.转换 前端的数据格式
        data_list = []
        skus = context['page'].object_list
        for sku in skus:
            data_list.append({
                'id': sku.object.id,
                'name': sku.object.name,
                'price': sku.object.price,
                'default_image_url': sku.object.default_image.url,
                'searchkey': query,
                # 'page_size': context['paginator'].num_pages,
                # 'count': context['paginator'].count,
                'page_size': context['page'].paginator.num_pages,
                'count': context['page'].paginator.count
            })

        # 4.返回 Json safe=False----默认 只能转换dict --list ---safe=False
        return JsonResponse(data_list, safe=False)


class DetailView(View):
    """商品详情页"""

    def get(self, request, sku_id):
        """提供商品详情页"""
        # 获取当前sku的信息
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return render(request, '404.html')

        # 查询商品频道分类
        categories = get_categories()
        # 查询面包屑导航
        breadcrumb = get_breadcrumb(sku.category)

        # 构建当前商品的规格键
        goods_specs = get_goods_specs(sku)

        # 渲染页面
        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'specs': goods_specs,
        }
        return render(request, 'detail.html', context)


class DetailVisitView(View):
    def post(self, request, category_id):

        # 1.接收参数 category_id
        # 2.校验参数
        try:
            cat3 = GoodsCategory.objects.get(pk=category_id)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '参数有误!'})

        # 3.判断 当天 有没有 这个分类的 记录数据
        from datetime import date
        today_date = date.today()

        try:
            # 1.GoodsVisitCount
            # goods_visit = GoodsVisitCount.objects.get(date=today_date, category=cat3)

            # 2,GoodsCategory
            goods_visit = cat3.goodsvisitcount_set.get(date=today_date)
        except Exception as e:
            # 如果没有  新建一条
            goods_visit = GoodsVisitCount()

        # 4.累加个数  += 1
        goods_visit.count += 1
        goods_visit.category = cat3
        goods_visit.save()

        # 5.返回Json
        return JsonResponse({'code': 0, 'errmsg': '记录成功!'})













